package com.tangding.controller.hprose;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Component;

import com.google.common.base.Strings;
import com.tangding.common.exception.GException;
import com.tangding.common.logx.LogHelp;
import com.tangding.common.tools.ErrorConstants;
import com.tangding.common.utils.JacksonUtil;

import hprose.client.HproseTcpClient;
import hprose.common.HproseException;

/**
 * @description 
 *
 * @author Ranger
 * @version 2017年11月16日_上午11:36:30
 *
 */
@Component
public class HproseHelper {
	
	static Map<String, HproseTcpClient> clientMap = new HashMap<>();
	
	static Map<String, String> clientHostMap = new HashMap<>();
	
	static String GAME_HOST = "tcp://localhost:4321/";

	@PostConstruct
	public void init() {
		clientHostMap.put("tangding", "tcp://localhost:4321/");
	}
	
	public static String getHost(String game) {
		return clientHostMap.get(game);
	}
	
	public static HproseTcpClient buildHproseTcpClient(String host) {
		HproseTcpClient client = new HproseTcpClient(host);
		client.setFullDuplex(true);
		client.setMaxPoolSize(1);
		client.setKeepAlive(true);
		return client;
	}
	
	public static Object invoke(String operate, String jsonParams) throws GException {
		HproseTcpClient client = buildHproseTcpClient(GAME_HOST);
		try {
			Object result = null;
			if (Strings.isNullOrEmpty(jsonParams)) {
				result = client.invoke(operate);
			}else {
				Map<String, Object> data = JacksonUtil.readValue(jsonParams, Map.class);
				result = client.invoke(operate, new Object[] {data});
			}
			return result;
		} catch (Throwable e) {
			LogHelp.doLogAppErr(operate + "|" + jsonParams + ":foward err!\r\n" + e.getMessage());
			if (e.getCause() instanceof HproseException) {
				throw new GException(ErrorConstants.ERR_FORWAR_NO_API);
			}else if (e.getCause() instanceof TimeoutException) {
				throw new GException(ErrorConstants.ERR_API_TIMEOUT);
			}else {
				throw new GException(ErrorConstants.ERR_FORWARD, operate + "|" + jsonParams + ":foward err!\r\n" + e.getMessage(), e);
			}
		}
	}
}
